package com.coolmusic;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class activity_register extends AppCompatActivity {
    private EditText etRegisterUsername, etRegisterPassword;
    private Button btnRegister;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initViews();
        initSharedPreferences();
        setupRegisterButton();
    }

    private void initViews() {
        etRegisterUsername = findViewById(R.id.et_username);
        etRegisterPassword = findViewById(R.id.et_password);
        btnRegister = findViewById(R.id.btn_register);
    }

    private void initSharedPreferences() {
        sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
    }

    private void setupRegisterButton() {
        btnRegister.setOnClickListener(v -> handleRegistration());
    }

    private void handleRegistration() {
        String username = etRegisterUsername.getText().toString().trim();
        String password = etRegisterPassword.getText().toString().trim();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (sharedPreferences.contains(username)) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
            return;
        }

        // 保存新用户信息
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(username, password); // 用户名作为key，密码作为value
        editor.apply();

        Toast.makeText(this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
        finish(); // 注册成功后返回登录界面
    }
}